<?php
namespace Admin\Controller;

class AdminController extends BaseController
{
    public function indexAction()
    {
        $Admin = D('Admin');
		$list = $Admin->order('id desc')->select();
		$this->assign('list', $list);
        $this->display();
    }
    
    public function addAction()
    {
        if (IS_POST) {
            $Admin = D('Admin');
            $data = $Admin->create($_POST['Admin']);
            if (false !== $data) {
                $insertId = $Admin->add();
                if (false !== $insertId) {
                    $this->success('新增成功', U('Admin/index'));
                } else {
                    $this->error('新增失败');
                }
            } else {
                $this->error($Admin->getError());
            }
        } else {
          $this->display();  
        }
    }

	public function updateAction()
    {
        $Admin = D('Admin');
		if (IS_POST) {
			if (!empty($_POST['Admin']['admin_password'])) {
                $admin_password = isset($_POST['Admin']['admin_password']) ? trim($_POST['Admin']['admin_password']) : '';
                $admin_password2 = isset($_POST['Admin']['admin_password2']) ? trim($_POST['Admin']['admin_password2']) : '';
                if ($admin_password !== $admin_password2) {
                    $this->error('两次输入密码不同！');
                }
                if (!$Admin->checkPassword($admin_password)) {
                    $this->error('密码格式有误！');
                }
                unset($_POST['Admin']['admin_password2']);
                $_POST['Admin']['admin_password'] = $Admin->password($_POST['Admin']['admin_password']);
                
                if ($Admin->save($_POST['Admin'])) {
                    $this->success('修改成功！', U('Admin/index'));
                } else {
                    $this->error('修改失败！');
                }
			} else {
				$res = $Admin->field('admin_name, admin_password', true)->create($_POST['Admin']);
				if (false !== $res) {
					if ($Admin->field('admin_name, admin_password', true)->save()) {
						$this->success('修改成功！', U('Admin/index'));
					} else {
						$this->error('修改失败！（失败原因：' . $Admin->getError() . '）');	
					}
				} else {
					$this->error($Admin->getError());
				}
			}
		} else {
            $id = I('get.id', 0, 'intval');
            $admin_info = $Admin->find($id);
            if (false === $admin_info) {
                $this->error('获取信息失败！');
            }
            $this->assign('admin_info', $admin_info);
            $this->display();  
		}
	}
    
    public function deleteAction()
    {
        $id = I('get.id', 0, 'intval');
        $Admin = M('Admin');
        if (false !== $Admin->delete($id)) {
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！');
        }
    }
}